<template>
  <div class="register-container">
    <!-- 左侧平台介绍（与登录页保持一致） -->
    <div class="platform-intro">
      <div class="logo-container">
        <img src="@/assets/logo.png" alt="健康预测平台" class="logo" />
        <h1>健康预测平台</h1>
      </div>
      <div class="feature-cards">
        <div class="feature-card">
          <div class="feature-icon">✓</div>
          <h3>专业医疗支持</h3>
          <p>基于医疗数据的精准分析和预测</p>
        </div>
        <div class="feature-card">
          <div class="feature-icon">📊</div>
          <h3>数据可视化</h3>
          <p>直观展示健康数据和趋势变化</p>
        </div>
      </div>
    </div>

    <!-- 右侧注册表单 -->
    <div class="register-form">
      <div class="form-header">
        <img src="@/assets/logo.png" alt="健康预测平台" class="form-logo" />
        <h2>用户注册</h2>
        <p>请填写以下信息完成注册</p>
      </div>

      <div class="form-group">
        <label for="username">用户名</label>
        <input 
          type="text" 
          v-model="registerForm.username" 
          id="username" 
          name="username"
          placeholder="请设置用户名" 
          class="form-control"
          :class="{ 'error': errors.username }"
        />
        <span v-if="errors.username" class="error-text">{{ errors.username }}</span>
      </div>

      <div class="form-group">
        <label for="idNumber">身份证号</label>
        <input 
          type="text" 
          v-model="registerForm.idNumber" 
          id="idNumber" 
          name="idNumber"
          placeholder="请输入身份证号" 
          class="form-control"
          :class="{ 'error': errors.idNumber }"
        />
        <span v-if="errors.idNumber" class="error-text">{{ errors.idNumber }}</span>
      </div>

      <div class="form-group">
        <label for="phone">联系电话</label>
        <input 
          type="tel" 
          v-model="registerForm.phone" 
          id="phone" 
          name="phone"
          placeholder="请输入手机号码" 
          class="form-control"
          :class="{ 'error': errors.phone }"
        />
        <span v-if="errors.phone" class="error-text">{{ errors.phone }}</span>
      </div>

      <div class="form-group">
        <label for="emergencyContact">紧急联系人姓名</label>
        <input 
          type="text" 
          v-model="registerForm.emergencyContact" 
          id="emergencyContact" 
          name="emergencyContact"
          placeholder="请输入紧急联系人姓名" 
          class="form-control"
          :class="{ 'error': errors.emergencyContact }"
        />
        <span v-if="errors.emergencyContact" class="error-text">{{ errors.emergencyContact }}</span>
      </div>

      <div class="form-group">
        <label for="emergencyPhone">紧急联系人电话</label>
        <input 
          type="tel" 
          v-model="registerForm.emergencyPhone" 
          id="emergencyPhone" 
          name="emergencyPhone"
          placeholder="请输入紧急联系人电话" 
          class="form-control"
          :class="{ 'error': errors.emergencyPhone }"
        />
        <span v-if="errors.emergencyPhone" class="error-text">{{ errors.emergencyPhone }}</span>
      </div>

      <div class="form-group">
        <label>居住省市</label>
        <div class="address-selector">
          <select 
            v-model="registerForm.provinceId" 
            @change="handleProvinceChange"
            class="form-control"
            :class="{ 'error': errors.provinceId }"
          >
            <option value="">请选择省份</option>
            <option v-for="province in provinces" :key="province.regionId" :value="province.regionId">
              {{ province.regionName }}
            </option>
          </select>
          <select 
            v-model="registerForm.cityId" 
            class="form-control"
            :class="{ 'error': errors.cityId }"
          >
            <option value="">请选择城市</option>
            <option v-for="city in cities" :key="city.regionId" :value="city.regionId">
              {{ city.regionName }}
            </option>
          </select>
        </div>
        <span v-if="errors.provinceId" class="error-text">{{ errors.provinceId }}</span>
        <span v-if="errors.cityId" class="error-text">{{ errors.cityId }}</span>
      </div>

      <div class="form-group">
        <label for="password">密码</label>
        <input 
          type="password" 
          v-model="registerForm.password" 
          id="password" 
          name="password"
          placeholder="请设置密码（至少6位）" 
          class="form-control"
          :class="{ 'error': errors.password }"
        />
        <span v-if="errors.password" class="error-text">{{ errors.password }}</span>
      </div>

      <div class="form-group">
        <label for="confirmPassword">确认密码</label>
        <input 
          type="password" 
          v-model="registerForm.confirmPassword" 
          id="confirmPassword" 
          name="confirmPassword"
          placeholder="请再次输入密码" 
          class="form-control"
          :class="{ 'error': errors.confirmPassword }"
        />
        <span v-if="errors.confirmPassword" class="error-text">{{ errors.confirmPassword }}</span>
      </div>

      <div class="terms-privacy">
        <input 
          type="checkbox" 
          id="terms" 
          name="terms"
          v-model="registerForm.agreeTerms" 
          class="form-checkbox"
          :class="{ 'error': errors.agreeTerms }"
        />
        <label for="terms">
          我已阅读并同意 <router-link to="/user-agreement">用户协议</router-link> 和 <router-link to="/privacy-policy">隐私政策</router-link>
        </label>
        <span v-if="errors.agreeTerms" class="error-text">{{ errors.agreeTerms }}</span>
      </div>

      <button @click="handleRegister" class="register-button">注册</button>
      
      <div class="register-footer">
        已有账号？<router-link to="/login">返回登录</router-link>
      </div>
    </div>
  </div>

</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'

import api from '../utils/axiosConfig'

// 路由实例
const router = useRouter()

// 注册表单数据
const registerForm = reactive({
  username: '',
  idNumber: '',
  phone: '',
  emergencyContact: '',
  emergencyPhone: '',
  provinceId: '',
  cityId: '',
  password: '',
  confirmPassword: '',
  agreeTerms: false
})

// 省份和城市数据
const provinces = ref([])
const cities = ref([])

// 错误信息
const errors = reactive({
  username: '',
  idNumber: '',
  phone: '',
  emergencyContact: '',
  emergencyPhone: '',
  provinceId: '',
  cityId: '',
  password: '',
  confirmPassword: '',
  agreeTerms: ''
})

// 验证表单
const validateForm = () => {
  let isValid = true
  const idReg = /(^\d{18}$)|(^\d{17}(\d|X|x)$)/
  const phoneReg = /^1[3-9]\d{9}$/
  
  // 清空之前的错误信息
  Object.keys(errors).forEach(key => {
    errors[key] = ''
  })
  
  // 用户名验证
  if (!registerForm.username.trim()) {
    errors.username = '请输入用户名'
    isValid = false
  } else if (registerForm.username.length < 2) {
    errors.username = '用户名至少2个字符'
    isValid = false
  }
  
  // 身份证号验证
  if (!registerForm.idNumber.trim()) {
    errors.idNumber = '请输入身份证号'
    isValid = false
  } else if (!idReg.test(registerForm.idNumber)) {
    errors.idNumber = '请输入有效的身份证号'
    isValid = false
  }
  
  // 手机号验证
  if (!registerForm.phone.trim()) {
    errors.phone = '请输入联系电话'
    isValid = false
  } else if (!phoneReg.test(registerForm.phone)) {
    errors.phone = '请输入有效的手机号码'
    isValid = false
  }
  
  // 紧急联系人验证
  if (!registerForm.emergencyContact.trim()) {
    errors.emergencyContact = '请输入紧急联系人姓名'
    isValid = false
  }
  
  // 紧急联系人电话验证
  if (!registerForm.emergencyPhone.trim()) {
    errors.emergencyPhone = '请输入紧急联系人电话'
    isValid = false
  } else if (!phoneReg.test(registerForm.emergencyPhone)) {
    errors.emergencyPhone = '请输入有效的紧急联系人电话'
    isValid = false
  }
  
  // 省份验证
  if (!registerForm.provinceId) {
    errors.provinceId = '请选择省份'
    isValid = false
  }
  
  // 城市验证
  if (!registerForm.cityId) {
    errors.cityId = '请选择城市'
    isValid = false
  }
  
  // 密码验证
  if (!registerForm.password) {
    errors.password = '请设置密码'
    isValid = false
  } else if (registerForm.password.length < 6) {
    errors.password = '密码长度至少6位'
    isValid = false
  }
  
  // 确认密码验证
  if (!registerForm.confirmPassword) {
    errors.confirmPassword = '请确认密码'
    isValid = false
  } else if (registerForm.password !== registerForm.confirmPassword) {
    errors.confirmPassword = '两次输入的密码不一致'
    isValid = false
  }
  
  // 协议同意验证
  if (!registerForm.agreeTerms) {
    errors.agreeTerms = '请阅读并同意用户协议和隐私政策'
    isValid = false
  }
  
  return isValid
}

// 处理注册
const handleRegister = async () => {
  // 表单验证
  if (!validateForm()) {
    return
  }
  
  try {
    // 准备注册数据，构建address字段
    const selectedProvince = provinces.value.find(p => p.regionId === registerForm.provinceId)
    const selectedCity = cities.value.find(c => c.regionId === registerForm.cityId)
    const address = `${selectedProvince?.regionName || ''}${selectedCity?.regionName || ''}`
    
    const registerData = {
      userName: registerForm.username,
      idCard: registerForm.idNumber,
      phone: registerForm.phone,
      emergencyName: registerForm.emergencyContact,
      emergencyPhone: registerForm.emergencyPhone,
      provinceId: registerForm.provinceId,
      cityId: registerForm.cityId,
      address: address, // 添加address字段，包含省份和城市信息
      password: registerForm.password, // 注意：实际项目中前端可能需要进行加密处理
      userType: 1 // 默认为普通用户
    }
    
    // 调用后端注册API
      const response = await api.post('/user', registerData)
    
    if (response.status === 200 || response.status === 201) {
      // 注册成功提示并跳转登录页
      alert('注册成功，请登录')
      router.push('/login')
    }
  } catch (error) {
    if (error.response) {
      // 后端返回错误信息
      let errorMessage = error.response.data.message || '注册失败，请稍后重试'
      
      // 根据不同错误字段显示具体错误
      if (error.response.data.errors) {
        const firstError = Object.values(error.response.data.errors)[0]
        errorMessage = Array.isArray(firstError) ? firstError[0] : firstError
      }
      
      // 显示第一个错误字段的错误信息
      Object.keys(errors).forEach(key => {
        if (error.response.data.errors && error.response.data.errors[key]) {
          errors[key] = error.response.data.errors[key]
        }
      })
      
      alert(errorMessage)
    } else {
      // 网络错误等
      alert('网络异常，请稍后重试')
      console.error('注册失败:', error)
    }
  }
}

// 处理省份变更
const handleProvinceChange = async () => {
  // 重置城市选择
  registerForm.cityId = ''
  cities.value = []
  
  // 如果选择了省份，获取对应的城市列表
  if (registerForm.provinceId) {
    try {
      const response = await api.get(`/regions/cities/${registerForm.provinceId}`)
      cities.value = response.data || []
    } catch (error) {
      console.error('获取城市列表失败:', error)
    }
  }
}

// 获取所有省份
const fetchProvinces = async () => {
  try {
    const response = await api.get('/regions/provinces')
    provinces.value = response.data || []
  } catch (error) {
    console.error('获取省份列表失败:', error)
  }
}

// 组件挂载时获取省份列表
onMounted(() => {
  fetchProvinces()
})
</script>

<style scoped>
.register-container {
  display: flex;
  min-height: 100vh;
  background-color: #f0f8ff;
  overflow: hidden;
}

/* 左侧平台介绍（与登录页样式统一） */
.platform-intro {
  flex: 1;
  background: linear-gradient(135deg, #0072c6 0%, #005a9e 100%);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 40px;
  color: #ffffff;
  position: relative;
  overflow: hidden;
}

.platform-intro::before {
  content: '';
  position: absolute;
  width: 300px;
  height: 300px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  top: -100px;
  right: 100px;
}

.platform-intro::after {
  content: '';
  position: absolute;
  width: 200px;
  height: 200px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  bottom: 50px;
  left: 50px;
}

.logo-container {
  text-align: center;
  margin-bottom: 60px;
  position: relative;
  z-index: 1;
}

.logo {
  width: 100px;
  height: 100px;
  margin-bottom: 20px;
  background-color: white;
  border-radius: 15px;
  padding: 10px;
}

.platform-intro h1 {
  font-size: 32px;
  font-weight: 700;
  margin: 0;
}

.feature-cards {
  display: flex;
  flex-direction: column;
  gap: 30px;
  width: 100%;
  max-width: 350px;
  position: relative;
  z-index: 1;
}

.feature-card {
  background-color: rgba(255, 255, 255, 0.1);
  padding: 25px;
  border-radius: 12px;
  text-align: center;
  -webkit-backdrop-filter: blur(10px);
    backdrop-filter: blur(10px);
  transition: transform 0.3s ease;
}

.feature-card:hover {
  transform: translateY(-5px);
}

.feature-icon {
  width: 60px;
  height: 60px;
  margin: 0 auto 15px;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}

.feature-card h3 {
  font-size: 20px;
  margin-bottom: 10px;
  margin-top: 0;
}

.feature-card p {
  font-size: 15px;
  opacity: 0.9;
  margin: 0;
}

/* 右侧注册表单 */
.register-form {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 40px;
  background-color: #ffffff;
  box-shadow: -5px 0 25px rgba(0, 0, 0, 0.05);
  overflow-y: auto;
  max-height: 100vh;
}

.form-header {
  text-align: center;
  margin-bottom: 40px;
  width: 100%;
  max-width: 350px;
}

.form-logo {
  width: 60px;
  height: 60px;
  margin-bottom: 15px;
}

.form-header h2 {
  font-size: 24px;
  color: #0072c6;
  margin-bottom: 10px;
  margin-top: 0;
}

.form-header p {
  font-size: 16px;
  color: #666666;
  margin: 0;
}

.form-group {
  width: 100%;
  max-width: 350px;
  margin-bottom: 20px;
  position: relative;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #333333;
  font-weight: 600;
  font-size: 15px;
}

.form-control {
  width: 100%;
  padding: 14px 16px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 16px;
  transition: all 0.3s ease;
}

.form-control:focus {
  outline: none;
  border-color: #0072c6;
  box-shadow: 0 0 0 3px rgba(0, 114, 198, 0.1);
}

.form-control.error {
  border-color: #e74c3c;
}

/* 省市选择器样式 */
.address-selector {
  display: flex;
  gap: 12px;
}

.address-selector select {
  flex: 1;
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  background-color: white;
  cursor: pointer;
}

.address-selector select:focus {
  outline: none;
  border-color: #0072c6;
  box-shadow: 0 0 0 2px rgba(0, 114, 198, 0.1);
}

.address-selector select.error {
  border-color: #f56c6c;
}

.error-text {
  display: block;
  color: #e74c3c;
  font-size: 13px;
  margin-top: 5px;
  padding-left: 2px;
}

.terms-privacy {
  display: flex;
  align-items: flex-start;
  margin-bottom: 25px;
  gap: 12px;
  padding: 15px;
  background-color: rgba(0, 114, 198, 0.05);
  border-radius: 12px;
  border: 1px solid rgba(0, 114, 198, 0.1);
  width: 100%;
  max-width: 350px;
}

.terms-privacy label {
  font-size: 14px;
  color: #444444;
  line-height: 1.6;
  font-weight: 500;
  flex: 1;
}

.terms-privacy a {
  color: #0072c6;
  text-decoration: none;
  font-weight: 600;
  position: relative;
}

.terms-privacy a::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 100%;
  height: 1px;
  background-color: #0072c6;
}

.terms-privacy a:hover {
  color: #005a9e;
}

.form-checkbox {
  margin-top: 4px;
  width: 18px;
  height: 18px;
  cursor: pointer;
}

.register-button {
  width: 100%;
  max-width: 350px;
  padding: 14px;
  background: linear-gradient(135deg, #0072c6 0%, #005a9e 100%);
  color: #ffffff;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-top: 10px;
}

.register-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(0, 114, 198, 0.3);
}

.register-footer {
  margin-top: 25px;
  text-align: center;
  color: #666666;
  font-size: 14px;
  width: 100%;
  max-width: 350px;
}

.register-footer a {
  color: #0072c6;
  text-decoration: none;
  font-weight: 600;
}

.register-footer a:hover {
  text-decoration: underline;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .register-container {
    flex-direction: column;
  }
  
  .platform-intro {
    padding: 30px 20px;
  }
  
  .feature-cards {
    max-width: 100%;
  }
  
  .register-form {
    padding: 30px 20px;
    max-height: none;
  }
}
</style>